package com.qd.system.service.log;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.api.service.ApManagerService;
import com.cdqidi.api.service.EnterpriseService;
import com.cdqidi.db.BaseService;
import com.qd.common.sys.domain.entity.log.ReceiveLogDTO;
import com.qd.system.mapper.ReceiveLogMapper;
import com.qd.system.model.ReceiveLog;
import com.qd.system.service.dict.MbUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

import static java.util.stream.Collectors.toList;

/**
 * 接收日志
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class ReceiveLogService extends BaseService<ReceiveLogMapper, ReceiveLog> {
    private final EnterpriseService enterpriseService;
    private final ApManagerService apManagerService;
    /**
     * 根据主键获取数据
     *
     * @param id 主键 
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public ReceiveLogDTO getByIdDto(String id) {
        return Optional.ofNullable(getById(id)).map(this::modelToDto).orElse(null);
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<ReceiveLogDTO> page(Page<ReceiveLog> page, ReceiveLogDTO dto) {
        final QueryWrapper<ReceiveLog> queryWrapper = createQueryWrapper(dto, "t1.");
        queryWrapper.orderByDesc("t1.add_time");
        queryWrapper.orderByAsc("t1.log_type");
        queryWrapper.orderByAsc("t1.app_id");
        final IPage<ReceiveLogDTO> iPage = baseMapper.page(page, queryWrapper);
        queryWrapper.clear();
        Optional.ofNullable(iPage.getRecords()).ifPresent(l -> l.forEach(this::buildDisplay));
        return iPage;
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public ReceiveLogDTO modelToDto(ReceiveLog model) {
        if (null == model) {
            return null;
        }
        final ReceiveLogDTO dto = new ReceiveLogDTO();
        dto.setId(model.getId());
        dto.setContent(model.getContent());
        dto.setReceiveTime(model.getReceiveTime());
        dto.setAddTime(model.getAddTime());
        dto.setErrMsg(model.getErrMsg());
        dto.setLogType(model.getLogType());
        dto.setAppId(model.getAppId());
        dto.setEId(model.getEId());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public ReceiveLog dtoToModel(ReceiveLogDTO dto) {
        if (null == dto) {
            return null;
        }
        final ReceiveLog model = new ReceiveLog();
        model.setId(dto.getId());
        model.setContent(dto.getContent());
        model.setReceiveTime(dto.getReceiveTime());
        model.setAddTime(dto.getAddTime());
        model.setErrMsg(dto.getErrMsg());
        model.setLogType(dto.getLogType());
        model.setAppId(dto.getAppId());
        model.setEId(dto.getEId());
        return model;
    }


    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(ReceiveLogDTO dto) {
        dto.setEIdDisplay(enterpriseService.idToDisplay(dto.getEId()));
        dto.setAppIdDisplay(apManagerService.idToDisplay(dto.getAppId()));
        dto.setLogTypeDisplay(MbUtil.idToDisplay(dto.getLogType()));
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<ReceiveLogDTO> modelToDtoList(List<ReceiveLog> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<ReceiveLog> createQueryWrapper(ReceiveLogDTO dto) {
        return createQueryWrapper(dto, "");
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<ReceiveLog> createQueryWrapper(ReceiveLogDTO dto, String tableAlias) {
        final QueryWrapper<ReceiveLog> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
        if (StringUtils.hasLength(tableAlias) && tableAlias.charAt(tableAlias.length() - 1) != '.') {
            tableAlias += ".";
        }
            if (StringUtils.hasLength(dto.getAppId())) {
                queryWrapper.eq(tableAlias + "app_id", dto.getAppId());
            }
            if (StringUtils.hasLength(dto.getEId())) {
                queryWrapper.eq(tableAlias + "e_id", dto.getEId());
            }
            if (StringUtils.hasLength(dto.getLogType())) {
                queryWrapper.eq(tableAlias + "log_type", dto.getLogType());
            }
        }
        return queryWrapper;
    }
}